<template>
   <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
         <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
         <el-breadcrumb-item>商城管理</el-breadcrumb-item>
         <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="hengxian"></div>

      <el-row>
         <el-col :span="3">
            <router-link to="/shop/products/create">
               <el-button type="primary" size="mini">
                  <i class="el-icon-plus"></i><span>新增</span>
               </el-button>
            </router-link>
            <el-button type="danger" size="mini" @click="handleDeleteMultiple">
               <i class="el-icon-delete"></i><span>删除</span>
            </el-button>
         </el-col>
         <el-col :span="3">
            <el-cascader placeholder="请选择分类" size="mini" :options="categories"
                         :props="props" v-model="category"
                         @change="handleSelectChange(category)" filterable>
            </el-cascader>
         </el-col>
         <el-col :span="4">
            <div>
               <el-checkbox-group v-model="check" size="mini" @change="handleChangeStatus(check)">
                  <el-checkbox-button v-for="item in status" :label="item.val" :key="item.val">{{item.name}}
                  </el-checkbox-button>
               </el-checkbox-group>
            </div>
         </el-col>
         <el-col :span="3">
            <el-select v-model="is_onsale" placeholder="上架状态" size="mini" @change="handleChangeOnSale(is_onsale)">
               <el-option label="全部" value=" "></el-option>
               <el-option label="上架" value="1"></el-option>
               <el-option label="下架" value="0"></el-option>
            </el-select>
         </el-col>
         <el-col :span="6">
            <div class="block">
               <el-date-picker v-model="date" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" size="mini"
                               @change="handleChangeDate(date)"
                               range-separator="至" start-placeholder="上架开始日期" end-placeholder="上架结束日期">
               </el-date-picker>
            </div>
         </el-col>
         <el-col :span="5">
            <div>
               <el-input placeholder="请输入内容" v-model="keyword" class="input-with-select" size="mini">
                  <el-select v-model="cate" slot="prepend" placeholder="请选择">
                     <el-option label="ID" value="id"></el-option>
                     <el-option label="名称" value="name"></el-option>
                  </el-select>
                  <el-button slot="append" @click="handleSearch" icon="el-icon-search"></el-button>
               </el-input>
            </div>
         </el-col>
      </el-row>

      <el-table ref="multipleTable" :data="products" tooltip-effect="dark" border style="width: 100%"
                @selection-change="handleSelectionChange" v-loading="loading">
         <el-table-column type="selection" width="39"></el-table-column>
         <el-table-column prop="id" label="ID"></el-table-column>
         <el-table-column prop="image" label="缩略图">
            <template slot-scope="scope">
               <img v-if="scope.row.image" :src="scope.row.image" @click="handleShow(scope.$index,scope.row)" alt=""
                    class="image">
            </template>
         </el-table-column>
         <el-table-column prop="name" label="商品名称"></el-table-column>
         <el-table-column prop="category_id" label="商品分类">
            <template slot-scope="scope">
               <el-tag v-if="scope.row.category_name" type="warning">{{ scope.row.category_name}}</el-tag>
            </template>
         </el-table-column>
         <el-table-column prop="price" label="单价"></el-table-column>
         <el-table-column prop="is_top" label="置顶" width="60">
            <template slot-scope="scope">
               <i :class="scope.row.is_top ? 'el-icon-success' : 'el-icon-error'"
                  @click="change_attr(scope.row,'is_top')"></i>
            </template>
         </el-table-column>
         <el-table-column prop="is_hot" label="热销" width="60">
            <template slot-scope="scope">
               <i :class="scope.row.is_hot ? 'el-icon-success' : 'el-icon-error'"
                  @click="change_attr(scope.row,'is_hot')"></i>
            </template>
         </el-table-column>
         <el-table-column prop="is_recommend" label="推荐" width="60">
            <template slot-scope="scope">
               <i :class="scope.row.is_recommend ? 'el-icon-success' : 'el-icon-error'"
                  @click="change_attr(scope.row,'is_recommend')"></i>
            </template>
         </el-table-column>
         <el-table-column prop="is_new" label="新品" width="60">
            <template slot-scope="scope">
               <i :class="scope.row.is_new ? 'el-icon-success' : 'el-icon-error'"
                  @click="change_attr(scope.row,'is_new')"></i>
            </template>
         </el-table-column>
         <el-table-column prop="is_onsale" label="上架" width="60">
            <template slot-scope="scope">
               <i :class="scope.row.is_onsale ? 'el-icon-success' : 'el-icon-error'"
                  @click="change_attr(scope.row,'is_onsale')"></i>
            </template>
         </el-table-column>
         <el-table-column prop="stock" label="库存" :label-width="formLabelWidth">
            <template slot-scope="scope">
               <el-input-number v-model="scope.row.stock"
                                @change="handleChange(scope.row.id,scope.row.stock,'stock')"
                                :min="1" :max="999" size="mini"></el-input-number>
            </template>
         </el-table-column>
         <el-table-column prop="sort_order" label="排序" :label-width="formLabelWidth">
            <template slot-scope="scope">
               <el-input-number v-model="scope.row.sort_order"
                                @change="handleChange(scope.row.id,scope.row.sort_order,'sort_order')"
                                :min="1" :max="999" size="mini"></el-input-number>
            </template>
         </el-table-column>
         <el-table-column prop="created_at" label="上架日期" width="170"></el-table-column>
         <el-table-column label="操作" width="100">
            <template slot-scope="scope">
               <router-link :to="{name:'products_edit',params: { id: scope.row.id }}">
                  <i class="el-icon-edit-outline"></i>
               </router-link>
               <i class="el-icon-delete" @click="handleDelete(scope.$index,scope.row)"></i>
            </template>
         </el-table-column>
      </el-table>

      <!--分页-->
      <div class="page">
         <span class="total">共 {{page.total}} 条数据</span>
         <el-pagination background :total="page.total" :page-size="page.size" @current-change="handleCurrentChange"
                        :current-page.sync="page.currentPage" layout="prev, pager, next">
         </el-pagination>
      </div>

      <!--查看大图-->
      <el-dialog :visible.sync="showImg" :width="width" custom-class="an-img-dialog" :center="true">
         <img :src="product.img" alt="" @load="onLoad">
      </el-dialog>
   </div>
</template>

<script>
   export default {
      name: "Home",
      data() {
         return {
            loading: false,
            showImg: false,
            width:'',
            status: [
               {name: '置顶', val: 'is_top'},
               {name: '热销', val: 'is_hot'},
               {name: '推荐', val: 'is_recommend'},
               {name: '新品', val: 'is_new'}
            ],
            check: [],
            is_onsale: '',
            date: [],
            products: [],
            multipleSelection: [],
            formLabelWidth: 120,
            categories: [],
            props: {
               expandTrigger: 'hover',
               value: 'id',
               label: 'name',
            },
            category: [],
            cate_id: '',
            keyword: '',
            cate: '',
            page: {
               total: 0,  //总数
               size: 0,  //每页显示数
               currentPage: 1,
            },
            product: {
               img: ''
            },
         }
      },
      created() {
         this.init();
      },
      methods: {
         onLoad(e){
            const img = e.target;
            let width = 0;
            if (img.fileSize > 0 || (img.width > 1 && img.height > 1)) {
               width = img.width + 50;
            }
            this.width = width + 'px';
         },
         //点击查看大图
         handleShow(index, row) {
            this.product.img = row.image;
            this.showImg = true;
         },
         //分页--获取当前页
         handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.page.currentPage = val;
            this.init();
         },
         //按分类搜索
         handleSelectChange(val) {
            // console.log(val[1]);
            this.cate_id = val[1];
            this.init();
         },
         //按状态搜索
         handleChangeStatus(val) {
            this.check = val;
            this.init();
         },
         //按上架状态搜索
         handleChangeOnSale(val) {
            this.is_onsale = val;
            this.init();
         },
         //按时间搜索
         handleChangeDate(val) {
            if (val != null) {
               this.date = val;
               this.init();
            }
         },
         //关键字搜索
         handleSearch() {
            this.init();
         },
         //首页
         init() {
            this.loading = true;
            const category_id = this.$route.params.category_id || this.cate_id;  //前者为查看分类发送过来的id,后者为默认值
            axios.get(`/admin/shop/products?page=${this.page.currentPage}&category_id=${category_id}&is_onsale=${this.is_onsale}
            &check=${this.check}&date=${this.date}&cate=${this.cate}&keyword=${this.keyword}`)
               .then((res) => {
                  this.products = res.data.data;
                  this.page.total = res.data.total;
                  this.page.size = res.data.per_page;
                  this.loading = false;
               });

            //所有分类
            axios.get(`/admin/shop/categories`)
               .then((res) => {
                  this.categories = res.data
               });
         },
         //改变属性
         change_attr(row, attr) {
            axios.patch(`/admin/shop/products/change_attr`, {id: row.id, attr: attr})
               .then((res) => {
                  this.$notify({
                     title: '成功',
                     message: '改变状态成功',
                     type: 'success'
                  });
                  this.init();
               });
         },
         //排序,改变库存
         handleChange(id, row, attr) {
            axios.patch(`/admin/shop/products/change`, {id: id, row: row, attr: attr})
               .then((res) => {
                  this.$message({
                     showClose: true,
                     message: '更新成功!',
                     type: 'success',
                  });
                  this.init();
               });
         },
         //删除
         handleDelete(index, row) {
            this.$confirm('确认删除该条商品,并同时删除商品相册?', '提示', {
               confirmButtonText: '确定',
               cancelButtonText: '取消',
               type: 'warning'
            }).then(() => {
               axios.delete(`/admin/shop/products/${row.id}`)
                  .then((res) => {
                     this.products.splice(index, 1);
                     this.$message({
                        type: 'success',
                        message: '删除成功!'
                     });
                     this.init();
                  });
            }).catch(() => {
               this.$message({
                  type: 'warning',
                  message: '已取消删除'
               });
            });
         },
         //获取选中的值
         handleSelectionChange(val) {
            this.multipleSelection = val;
         },
         //多选删除
         handleDeleteMultiple() {
            if (this.multipleSelection.length == 0) {
               this.$message({
                  message: '至少选择一条数据',
                  type: 'warning'
               });
            } else {
               this.$confirm('此操作将永久删除该商品并同时删除商品相册, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
               }).then(() => {
                  const checked_id = this.multipleSelection.map((item) => {
                     return item.id;
                  });
                  axios.post(`/admin/shop/products/delete_all`, {checked_id: checked_id})
                     .then((res) => {
                        this.$message({
                           type: 'success',
                           message: '删除成功!'
                        });
                        this.init();
                     });
               }).catch(() => {
                  this.$message({
                     type: 'info',
                     message: '已取消删除'
                  });
               });
            }
         },
      },
   }
</script>

<style>
   .el-row {
      margin-bottom: 15px;
   }

   .el-select {
      width: 130px;
   }

   .image {
      width: 80px;
      height: 30px;
      cursor: pointer;
   }

   .input-with-select .el-input-group__prepend {
      background-color: #fff;
   }


   .el-table td {
      padding: 3px 0;
   }

   .el-input__inner {
      padding: 0 2px;
   }

</style>